package com.nongxiange.unittesttutorial.spring.bean;

import lombok.Data;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 增强实现
 * 通过FactoryBean创建一个代理类来增强目标类
 */
@Data
public class MyFactoryBeanPlus implements FactoryBean, InitializingBean, DisposableBean {

    private Object proxyObject;
    private Object target;
    private String interfaceName;

    @Override
    public Object getObject() throws Exception {
        return proxyObject;
    }

    @Override
    public Class<?> getObjectType() {
        return proxyObject.getClass()==null ? Object.class : proxyObject.getClass();
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("destroy ....");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("--afterPropertiesSet--");
        proxyObject = Proxy.newProxyInstance(this.getClass().getClassLoader(),
                new Class[]{Class.forName(interfaceName)},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("--代理方法执行开始--");
                        Object obj = method.invoke(target, args);
                        System.out.println("--代理方法执行结束--");
                        return obj;
                    }
                });
    }
}